package com.lu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lu.model.common.dtos.ResponseResult;
import com.lu.model.common.enums.AppHttpCodeEnum;
import com.lu.model.user.dto.LoginDto;
import com.lu.model.user.pojo.ApUser;
import com.lu.user.mapper.ApUserMapper;
import com.lu.user.service.ApUserService;
import com.lu.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 用户登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //手机号和密码都不能为空
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {
            //对比密码
            LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper();
            wrapper.eq(ApUser::getPhone, dto.getPhone());
            ApUser apUser = this.getOne(wrapper);
            //ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            System.out.println(apUser);
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在!");
            }
            String salt = apUser.getSalt();
            String pwd = dto.getPassword();
            pwd = DigestUtils.md5DigestAsHex((pwd + salt).getBytes());
            if (!pwd.equals(apUser.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //授予token令牌
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            apUser.setSalt("");
            apUser.setPassword("");
            map.put("user", apUser);
            return ResponseResult.okResult(map);
            //游客登陆
        } else {
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }
}
